import AuditmainAPI from '../../common/api/biosafety/auditmain.api.js';
import saleOrdersAPI from '../../common/api/breedsales/orderbills.api.js';
import { DictionaryType, requestDict } from '../../common/dictionary/dictionary-type.js';
import { Select2Page } from '../../common/serve-request.js';
import { uploadFile, requestFilePath, publicFileDraw, sliceFileName } from '../../common/api/file-request.js';

(function (window, document, $) {
    let _vm,
        savetype,
        entriesmater,
        getEntryInfo = [],
        nextEntryId = 1,
        operaEntryId,
        saveEntry,
        checkSale,
        _specLevelArry = [];
    const BaseCfgUrl = Utils.CurDomain.BaseCfgUrl;
    const _json = Utils.ParsingUrl(window.location);
    let resultInfo = [],
        personList = [];
    $(async function () {
        _vm = new Vue({
            el: '#saleordersentry-form',
            data() {
                return {
                    entries: [
                        {
                            isHave: false,
                            seq: '',
                            auditItemId: '',
                            text: '',
                            weight: '',
                            isQualified: false,
                            isRectify: false,
                            deduct: '',
                            reason: '',
                            suggestion: '',
                            principal: '',
                            principalIds: '',
                            principalNames: '',
                            timeLimit: '',
                            result: '',
                            image: '',
                            remark: '',
                        },
                    ],
                    attaches: [],
                    images: [],
                    uploadCount: 0,
                };
            },
            methods: {
                submit() {
                    savedata();
                },
            },
        });
        await initSelectValue();
        _initCommand();
        uploadInit();

        $(document).on('mousedown', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $(document).on('focus', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
    });

    // 初始化数据
    const _initCommand = async () => {
        getEntryInfo = JSON.parse(Utils.GetSessionStorage('getEntryInfo')) || [];
        let seqId = getUrlKey('operaEntryId');

        // 编辑赋值
        if (seqId) {
            $('title').text('生物安全审查明细-编辑');
            let datas = getEntryInfo.find((item) => item.seq == seqId);
            const propertiesToCopy = ['isHave', 'auditItemId', 'text', 'weight', 'isQualified', 'isRectify', 'deduct', 'reason', 'suggestion', 'principal', 'principalIds', 'principalNames', 'timeLimit', 'result', 'image', 'remark'];
            propertiesToCopy.reduce((obj, prop) => {
                _vm.entries[0][prop] = datas[prop];
            }, {});

            $('#result').val(_vm.entries[0].result).trigger('change');
            if (_vm.entries[0].principalIds.includes(',')) {
                let newlist = _vm.entries[0].principalIds.split(',');
                $('#principal').val(newlist).trigger('change');
            } else {
                $('#principal').val(_vm.entries[0].principalIds).trigger('change');
            }
            let scorerinfo = cutstr(_vm.entries[0].principal, 30); // 截取字符串
            $('#principal').next('.select2-container').find('.select2-selection__rendered').text(scorerinfo);
            $('#principal').next('.select2-container').find('.select2-selection__rendered').css({ 'text-align': 'left' });
            $('#principalIds').val(_vm.entries[0].principalIds);
            $('#principalNames').val(_vm.entries[0].principal);

            _vm.entries[0].principalIds = $('#principalIds').val();
            _vm.entries[0].principalNames = $('#principalNames').val();

            $('input[name="isQualified"][value="' + _vm.entries[0].isQualified + '"]').prop('checked', true);
            $('input[name="isRectify"][value="' + _vm.entries[0].isRectify + '"]').prop('checked', true);
            if (Utils.IsNotNull(_vm.entries[0].image)) {
                if ((_vm.entries[0].image || '').includes(',')) {
                    _images(_vm.entries[0].image.split(','));
                } else {
                    _images([_vm.entries[0].image]);
                }
            }
        }

        //取消按钮，返回列表
        $(document).on('click', '#returnMain', function () {
            if (Utils.IsNotNull(getUrlKey('id'))) {
                location.href = `../biosafety/addsaveauditmain.html?v=${Utils.GetTime()}&mainId=${getUrlKey('id')}`;
            } else {
                location.href = `../biosafety/addsaveauditmain.html?v=${Utils.GetTime()}`;
            }
        });

        // 上传附件
        $('#uploaderFiles').click(function (e) {
            let target = e.target;
            while (!target.classList.contains('weui-uploader__file') && target) {
                target = target.parentNode;
            }
            if (!target) return;
            //从图片对应的li标签中获得所需属性
            let gallery = weui.gallery($(target).attr('data-url'), {
                className: 'custom-name',
                onDelete: function () {
                    //删除图片的回调
                    $.confirm({
                        title: '删除提示',
                        text: '确定删除该图片？',
                        onOK: function () {
                            let _id = $(target).attr('data-id');
                            _vm.images = _vm.images.filter((item) => item.id != _id);
                            _vm.uploadCount = --_vm.uploadCount;
                            target.remove();
                            gallery.hide();
                            // 添加3张后隐藏上传按钮
                            if (_vm.uploadCount == 3) {
                                $('.weui-uploader__input-box').hide();
                            } else {
                                $('.weui-uploader__input-box').show();
                            }
                        },
                        onCancel: function () {},
                    });
                },
            });
        });
    };

    // 保存
    const savedata = () => {
        if (!Utils.IsNotNull($(`#text`).val())) {
            return $.toptip(`请选择审查内容!`, 'warning');
        }
        if (!Utils.IsNotNull($(`#weight`).val())) {
            return $.toptip(`请输入权重分!`, 'warning');
        }
        let seq = parseInt(getUrlKey('operaEntryId'));
        let entriesmater = {
            isHave: false,
            seq: _vm.entries[0].seq,
            auditItemId: _vm.entries[0].auditItemId,
            text: $(`#text`).val(),
            weight: $(`#weight`).val(),
            isQualified: $('input[name="isQualified"]:checked').val(), // 获取单选框的值
            isRectify: $('input[name="isRectify"]:checked').val(),
            deduct: $(`#deduct`).val(),
            reason: $(`#reason`).val(),
            suggestion: $(`#suggestion`).val(),
            principal: $(`#principalNames`).val(),
            principalIds: $(`#principalIds`).val(),
            timeLimit: $(`#timeLimit`).val(),
            result: $(`#result`).val(),
            image: _vm.attaches.join(','),
            remark: $(`#remark`).val(),
        };
        let savetype;
        if (seq) {
            savetype = '修改';
        } else {
            savetype = '保存';
        }

        $.modal({
            autoClose: false,
            title: '提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
    				<div class="" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
    					<div>是否确认${savetype}该分录？</div>
    				</div>`,
            buttons: [
                {
                    text: '取消',
                    className: 'default',
                    onClick: function () {
                        $.closeModal();
                    },
                },
                {
                    text: '保存',
                    onClick: function () {
                        if (seq) {
                            // 编辑
                            let index = getEntryInfo.findIndex((s) => s.seq == seq);
                            getEntryInfo[index] = entriesmater;
                        } else {
                            // 新增
                            entriesmater.seq = getEntryInfo.length + 1;
                            entriesmater.auditItemId = entriesmater.seq;
                            getEntryInfo.push(entriesmater);
                        }

                        // 存入SessionStorage
                        JSON.stringify(Utils.SetSessionStorage('getEntryInfo', getEntryInfo));
                        if (Utils.IsNotNull(getUrlKey('id'))) {
                            location.href = `../biosafety/addsaveauditmain.html?v=${Utils.GetTime()}&mainId=${getUrlKey('id')}`;
                        } else {
                            location.href = `../biosafety/addsaveauditmain.html?v=${Utils.GetTime()}`;
                        }
                        $.closeModal();
                    },
                },
            ],
        });
    };

    //TODO :初始化下拉框内容
    const initSelectValue = async () => {
        // 选择日期
        $('#timeLimit-date').on('click', function () {
            pickIsolationDate();
        });

        // 获取人员列表
        // await AuditmainAPI.getPersonList().then(res => {
        //     personList = res.items.map(item => {
        //         return { ...item, text: item.name }
        //     })
        //     $('#principal').empty().select2({
        //         placeholder: '请选择负责人...', //默认文字提示
        //         language: "zh-CN",//汉化
        //         allowClear: true,//允许清空
        //         data: personList,
        //     });
        //     $('#principal').setSelectValue();
        // })
        $(`#principal`)
            .empty()
            .select2({
                language: 'zh-CN',
                allowClear: true, //允许清空
                placeholder: '请选择员工...', //默认文字提示
                ajax: {
                    url: Utils.CurDomain.EmployeeMgtUrl + `/emplrecds/by/q`,
                    dataType: 'json',
                    type: 'GET',
                    beforeSend: Utils.AjaxBeforeSend,
                    data: function (params) {
                        return {
                            Status: true,
                            // SearchInfo: params.term,
                            PageSize: 20,
                            PageIndex: (params.page || 1) - 1,
                            ...(Utils.IsNotNull(params.term) ? { SearchInfo: params.term } : {}),
                        };
                    },
                    processResults: function (data, params) {
                        params.page = params.page || 1;
                        let _data = data.data.items.map((item) => {
                            item.text = `${item.name}(${item.numCode})`;
                            return item;
                        });
                        return {
                            results: _data, // 后台返回的数据集
                            pagination: {
                                more: params.page < data.data.totalPages, // 总页数为10，那么1-9页的时候都可以下拉刷新
                            },
                        };
                    },
                    minimumInputLength: 1,
                    cache: true,
                    delay: 700, //等待用户输入完后的 在等700毫秒 进行搜索
                    error: Utils.AjaxError,
                },
            });
        $('#principal').setSelectValue();
        // 选择
        $('#principal').on('select2:select', function () {
            let list = $(this).select2('data');
            $('#principalIds').val(
                list
                    .map((item) => {
                        return item.id;
                    })
                    .join(','),
            );
            $('#principalNames').val(
                list
                    .map((item) => {
                        return item.text;
                    })
                    .join(','),
            );

            _vm.entries[0].principalIds = $('#principalIds').val();
            _vm.entries[0].principalNames = $('#principalNames').val();
            _vm.entries[0].principal = $('#principalNames').val();

            let saleOrgsinfo = cutstr($('#principalNames').val(), 30); // 截取字符串
            $(this).next('.select2-container').find('.select2-selection__rendered').text(saleOrgsinfo);
            $(this).next('.select2-container').find('.select2-selection__rendered').css({ 'text-align': 'left' });
        });

        // 整改情况
        await requestDict(DictionaryType.RESULT_TYPE).then((res) => {
            resultInfo = _.cloneDeep(res.data);
            $('#result')
                .empty()
                .select2({
                    placeholder: '请选择整改情况...', //默认文字提示
                    language: 'zh-CN', //汉化
                    allowClear: true, //允许清空
                    data: res.data.map((item) => {
                        return {
                            id: item.value,
                            text: item.displayName,
                        };
                    }),
                });
            $('#result').setSelectValue();
        });
        // 选择
        $('#result').on('select2:select', function () {
            _vm.entries[0].result = $(this).select2('data')[0]?.id;
        });
    };

    // 获取地址栏的参数
    const getUrlKey = (name) => {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    };

    // 解决字段过长
    const cutstr = (str, len) => {
        var str_length = 0;
        var str_len = 0;
        var str_cut = new String();
        str_len = str.length;
        for (var i = 0; i < str_len; i++) {
            var a = str.charAt(i);
            str_length++;
            if (escape(a).length > 4) {
                //中文字符的长度经编码之后大于4
                str_length++;
            }
            str_cut = str_cut.concat(a);
            if (str_length >= len) {
                str_cut = str_cut.concat('...');
                return str_cut;
            }
        }
        //如果给定字符串小于指定长度，则返回源字符串；
        if (str_length < len) {
            return str;
        }
    };

    // 附件上传
    const uploadInit = () => {
        weui.uploader('#uploader', {
            url: '',
            auto: false,
            type: 'file',
            compress: { isNoTCompress: true },
            onBeforeQueued: function (files) {
                // `this` 是轮询到的文件, `files` 是所有文件
                if (['image/jpg', 'image/jpeg', 'image/png'].indexOf(this.type) < 0) {
                    $.toptip('请上传图片', 'warning');
                    return false; // 阻止文件添加
                }
                if (this.size > 8 * 1024 * 1024) {
                    $.toptip('请上传不超过8M的文件', 'warning');
                    return false;
                }
                $.showLoading('上传中..');
                _vm.uploadCount = ++_vm.uploadCount;
                if (_vm.uploadCount == 3) {
                    $('.weui-uploader__input-box').hide();
                }
            },
            onQueued: function () {
                let formFile = new FormData();
                let upFiles = this;
                let file = publicFileDraw(this.name, _vm);
                $.showLoading('上传中...');
                let fileName = sliceFileName(upFiles);
                let newfile = publicFileDraw(fileName, _vm);
                if (newfile != false && newfile != undefined) {
                    formFile.append('apiobjfile', new window.File([upFiles], newfile, { type: upFiles.type }));
                    _uploadFileDraw(formFile, upFiles, _vm, newfile);
                }
                // if (file != false && file != undefined) {
                //     formFile.append('apiobjfile', new window.File([this], file, { type: this.type }));
                //     _uploadFileDraw(formFile, upFiles, _vm, file);
                // }
                // //确认提交
                // $('.weui-dialog__btn').on('click', function () {
                //     if ($(this)[0].innerHTML == '确认') {
                //         $.showLoading('上传中...');
                //         let fileName = sliceFileName(upFiles);
                //         let newfile = publicFileDraw(fileName, _vm);
                //         if (newfile != false && newfile != undefined) {
                //             formFile.append('apiobjfile', new window.File([upFiles], newfile, { type: upFiles.type }));
                //             _uploadFileDraw(formFile, upFiles, _vm, newfile);
                //         }
                //     }
                // });
                return true;
            },
        });
        $('#uploaderFiles').click(function (e) {
            let target = e.target;
            while (!target.classList.contains('weui-uploader__file') && target) {
                target = target.parentNode;
            }
            if (!target) return;
            //从图片对应的li标签中获得所需属性
            let gallery = weui.gallery($(target).attr('data-url'), {
                className: 'custom-name',
                onDelete: function () {
                    //删除图片的回调
                    $.confirm({
                        title: '删除提示',
                        text: '确定删除该图片？',
                        onOK: function () {
                            let _id = $(target).attr('data-id');
                            _vm.images = _vm.images.filter((item) => item.id != _id);
                            _vm.uploadCount = --_vm.uploadCount;
                            target.remove();
                            gallery.hide();
                            // 添加3张后隐藏上传按钮
                            if (_vm.uploadCount == 3) {
                                $('.weui-uploader__input-box').hide();
                            } else {
                                $('.weui-uploader__input-box').show();
                            }
                        },
                        onCancel: function () {},
                    });
                },
            });
        });
    };

    // 附件上传
    const _uploadFileDraw = (formFile, upFiles, _vm, newName) => {
        uploadFile(formFile)
            .then((res) => {
                if (res.isSucceed) {
                    let _list = _vm.images;
                    _list.push({
                        id: $('#uploaderFiles li').length,
                        imageId: res.data,
                        url: upFiles.url,
                        name: newName,
                    });
                    _vm.attaches.push(res.data);
                    $('#uploaderFiles li').each(function (i) {
                        $(this).attr('data-id', _vm.images[i].id);
                        $(this).attr('data-image-id', _vm.images[i].imageId);
                        $(this).attr('data-name', _vm.images[i].name);
                        $(this).attr('data-suffix', _vm.images[i].type);
                        $(this).attr('data-url', _vm.images[i].url);
                        $(this).css({ 'background-image': `url(${_vm.images[i].url})` });
                    });
                    $('.weui-uploader__file-content').hide();
                    $('.weui-uploader__file').removeClass('weui-uploader__file_status');
                    $.hideLoading();
                    $.closeModal();
                }
            })
            .catch((res) => {
                $('#uploaderFiles li')
                    .eq($('#uploaderFiles li').length - 1)
                    .remove();
                _vm.uploadCount = --_vm.uploadCount;
                $.toptip(res.msg, 'error');
            })
            .finally((_) => {
                $.hideLoading();
                $.closeModal();
            });
    };
    // 编辑回写
    const _images = async (file) => {
        let _imag = file;
        if (_imag) {
            if (!uploader) {
                await uploadInit();
            }
            let _sun = 0;
            for (let i = 0; i < _imag.length; i++) {
                if (typeof _imag[i] !== 'object') {
                    ++_sun;
                    _vm.uploadCount = _sun;
                    await requestFilePath(_imag[i]).then((_res) => {
                        let _list = _vm.images;
                        _list.push({
                            id: _sun,
                            url: _res.data,
                            imageId: _imag[i],
                        });
                        if (_res.isSucceed) {
                            let _li;
                            if (['jpg', 'jpeg', 'png', 'gif'].indexOf(_imag[i].suffix) < 0) {
                                _li = `<li class="weui-uploader__file"  data-id="${_sun}" data-url="${_res.data}" data-image-id="${_imag[i]}" style="background-image: url(${_res.data}) "></li>`;
                            } else {
                                _li = `<li class="weui-uploader__file" data-id="${_sun}" data-url="${_res.data}" data-image-id="${_imag[i]}" style="background-image: url(${_res.data}) "></li>`;
                            }
                            $('#uploaderFiles').append(_li);
                        }
                    });
                }
                if (_sun == 3) {
                    $('.weui-uploader__input-box').hide();
                }
            }
        }
    };

    // 时间选择器
    const pickIsolationDate = () => {
        weui.datePicker({
            defaultValue: moment(new Date()).format('YYYY-MM-DD').split('-'),
            // end: moment(new Date()).format('YYYY-MM-DD'),
            className: 'mypick',
            onConfirm: async function (result) {
                // let value = `${result[0].value}-${result[1].value}-${result[2].value}`;
                let value = result.map((item) => item.value).join('-');
                // $('#timeLimit').val(moment(new Date(value)).format('YYYY-MM-DD'));
                _vm.entries[0].timeLimit = result.map((item) => item.value).join('-');
            },
        });
    };
})(window, document, jQuery);
